package com.gree.flowable.app.services.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gree.flowable.app.mapper.CreateTablesMapper;
import com.gree.flowable.app.mapper.FormModelMapper;
import com.gree.flowable.app.pojo.ex.ApplySubmitPO;
import com.gree.flowable.app.pojo.form.FormModel;
import com.gree.flowable.app.pojo.form.MySQLColumnVO;
import com.gree.flowable.app.pojo.vo.ReturnVO;
import com.gree.flowable.app.services.IFormImportExcelService;
import com.gree.flowable.app.tools.constants.ReturnCode;
import com.gree.flowable.app.tools.utils.SheetHandler;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xssf.eventusermodel.XSSFReader;
import org.apache.poi.xssf.eventusermodel.XSSFSheetXMLHandler;
import org.apache.poi.xssf.model.SharedStringsTable;
import org.apache.poi.xssf.model.StylesTable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;

import java.io.InputStream;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * @author ：180849
 * @date ：Created in 2021/5/11 11:41
 * @description：批量建单的Excel导入解析
 * @modified By：
 * @version: 1.0
 */
@Service
public class IFormImportExcelServiceImpl implements IFormImportExcelService {

    @Autowired
    private FormModelMapper formModelMapper;

    @Autowired
    private CreateTablesMapper createTablesMapper;

    /**
     * 导入Excel
     *
     * @param file       文件
     * @param formId     表单id
     * @param processKey 流程定义的key
     * @return 创建的条数
     */
    @Override
    public List<ApplySubmitPO> importForm(MultipartFile file, String formId, String processKey) throws Exception{
        //获取导出Excel的list集合
        QueryWrapper<FormModel> formModelQueryWrapper = new QueryWrapper<>();
        formModelQueryWrapper.lambda().eq(FormModel::getFormId,formId).orderByAsc(FormModel::getSort);
        List<FormModel> formModelList = formModelMapper.selectList(formModelQueryWrapper);
//        columnMap.put("formName","单据主题formName");
        List<Map<String,String>> resultColumnList = new LinkedList<>();
        //设置单据主题
        Map<String,String> themeMap = new HashMap<>(16);
        themeMap.put("field","formName");
        themeMap.put("name","单据主题");
        resultColumnList.add(themeMap);
        Map<String,String> dataTypeMap = new HashMap<>(16);
        for (FormModel formModel :formModelList) {
            Map<String, String> columnMap = new HashMap<>(16);

            columnMap.put("field", formModel.getFields());
            columnMap.put("name", formModel.getLabel());
            MySQLColumnVO mySQLColumnVO = createTablesMapper.queryColumnsInMySQLByColumn(formId, formModel.getFields());
//            columnMap.put("dataType",mySQLColumnVO.getDataType());
            //判断是否时时间类型
            if ("bigint".equals(mySQLColumnVO.getDataType())){
                dataTypeMap.put("field",mySQLColumnVO.getColumnName());
                dataTypeMap.put("dataType",mySQLColumnVO.getDataType());
            }
            resultColumnList.add(columnMap);
//            columnMap.put(formModel.getFields(),formModel.getLabel()+formModel.getFields());
        }


        //1.根据Excel报表获取OPCPackage
        InputStream inputStream = file.getInputStream();
        OPCPackage opcPackage = OPCPackage.open(inputStream);
        // 2.创建XSSFReader
        XSSFReader xssfReader = new XSSFReader(opcPackage);
        // 3.获取SharedStringTable对象
        SharedStringsTable sharedStringsTable = xssfReader.getSharedStringsTable();
        // 4.获取styleTable对象
        StylesTable stylesTable = xssfReader.getStylesTable();
        // 5.创建sax xmlReader对象
        XMLReader xmlReader = XMLReaderFactory.createXMLReader();
        // 6.注册事件驱动处理器
        SheetHandler sheetHandler = new SheetHandler(resultColumnList,dataTypeMap);
        XSSFSheetXMLHandler xssfSheetXMLHandler = new XSSFSheetXMLHandler(stylesTable, sharedStringsTable, sheetHandler, false);
        xmlReader.setContentHandler(xssfSheetXMLHandler);
        // 7.逐行读取
        XSSFReader.SheetIterator sheetIterator = (XSSFReader.SheetIterator) xssfReader.getSheetsData();
        while (sheetIterator.hasNext()) {
            InputStream in = sheetIterator.next();
            InputSource is = new InputSource(in);
            xmlReader.parse(is);
        }
        // 解析出所有数据
        List<Map<String, Object>> employeeList = sheetHandler.getMapsList();
        List<ApplySubmitPO> applySubmitPOList = new LinkedList<>();
        for (Map<String, Object> map: employeeList){

            ApplySubmitPO applySubmitPO = new ApplySubmitPO();
            applySubmitPO.setFormName(map.get("formName").toString());
            map.keySet().removeIf(key -> !"formName".equals(key));
            applySubmitPO.setData(map);
            applySubmitPO.setFormId(formId);
            applySubmitPO.setProcessDefinitionKey(processKey);
            applySubmitPOList.add(applySubmitPO);
        }
        return applySubmitPOList;
    }

    /**
     * 获取Excel的表单表头
     *
     * @param formId     表单id
     * @param processKey 流程定义的key
     * @return
     */
    @Override
    public ReturnVO<Map<String,Object>> getExcelHead(String formId, String processKey) {
        //获取导出Excel的list集合
        QueryWrapper<FormModel> formModelQueryWrapper = new QueryWrapper<>();
        formModelQueryWrapper.lambda().eq(FormModel::getFormId,formId).orderByAsc(FormModel::getSort);
        List<FormModel> formModelList = formModelMapper.selectList(formModelQueryWrapper);
//        columnMap.put("formName","单据主题formName");
        List<Map<String,String>> resultColumnList = new LinkedList<>();
        //设置单据主题
        Map<String,String> themeMap = new HashMap<>(16);
        themeMap.put("field","formName");
        themeMap.put("name","单据主题");
        themeMap.put("fieldType","String");
        resultColumnList.add(themeMap);
//        List<Map<String,String>> dataTypeList = new LinkedList<>();
        for (FormModel formModel :formModelList) {
//            Map<String,String> dataTypeMap = new HashMap<>(16);
            Map<String, String> columnMap = new HashMap<>(16);

            columnMap.put("field", formModel.getFields());
            columnMap.put("name", formModel.getLabel());
            columnMap.put("fieldType",formModel.getFieldType());
//            MySQLColumnVO mySQLColumnVO = createTablesMapper.queryColumnsInMySQLByColumn(formId, formModel.getFields());
//            columnMap.put("dataType",mySQLColumnVO.getDataType());
            //判断是否时时间类型
//            if ("bigint".equals(mySQLColumnVO.getDataType())){
//            dataTypeMap.put("field", mySQLColumnVO.getColumnName());
//            dataTypeMap.put("dataType", mySQLColumnVO.getDataType());
//            dataTypeList.add(dataTypeMap);
//            }
            resultColumnList.add(columnMap);
//            columnMap.put(formModel.getFields(),formModel.getLabel()+formModel.getFields());
        }
        ReturnVO<Map<String,Object>> result = null;
        Map<String,Object> excelHeardMap = new HashMap<>();
        Map<String,String> formTheme = new HashMap<>();
//        formTheme.put("field","formName");
//        dataTypeList.add(formTheme);
//        excelHeardMap.put("dateTypeList",dataTypeList);
        excelHeardMap.put("columnList",resultColumnList);
        if (excelHeardMap.size() > 0){
            result = new ReturnVO<>(ReturnCode.SUCCESS,"Excel表头获取成功",excelHeardMap);
        } else {
            result = new ReturnVO<>(ReturnCode.FAIL,"Excel表头获取失败",excelHeardMap);
        }
        return result;
    }
}
